package vip.meeet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import vip.meeet.elasticsearch.bean.ScrollResponse;
import vip.meeet.utils.ESUtil;
import vip.meeet.utils.HttpUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

public final class DocHelper {

    /**
     * 添加文档
     * @param hostPort
     * @param index
     * @param id
     * @param jsonBody
     * @throws IOException
     */
    public static String addDoc(String hostPort,String index,String id,String jsonBody) throws IOException {
        String urlBase = "http://%s/%s/_doc/%s";
        String url = String.format(urlBase, hostPort,index, id);
        String rs = HttpUtil.putJsonContent(url, jsonBody);
        return rs;
    }

    /**
     * 获取指定id文档
     * curl -XGET 'http://localhost:9200/index/id'
     * @param hostPort
     * @param index
     * @param id
     * @return
     * @throws IOException
     */
    public static String getDoc(String hostPort,String index,String id) throws IOException {
        String urlBase = "http://%s/%s/_doc/%s";
        String url = String.format(urlBase, hostPort,index, id);
        String content = HttpUtil.getContent(url);
        return content;
    }

    /**
     * curl -H 'Content-Type:application/json' -d '{"query":{"match_all":{}}}' http://host:port/index/_search?scroll=10m&search_type=scan
     * @param hostPort
     * @param index
     * @param time e.g. 10m,30s etc
     */
    public static void printAllDoc(String hostPort,String index,String time) throws IOException {
        Optional<ScrollResponse> scrollResponseOptional = scrollSource(hostPort, index, time);
        ScrollResponse scrollResponse;
        String lastScrollId = null;
        while (scrollResponseOptional.isPresent()) {
            scrollResponse = scrollResponseOptional.get();
            if(scrollResponse.getSources().size() == 0){
                break;
            }
            lastScrollId = scrollResponse.getScrollId();
            System.out.println(lastScrollId);
            List<JSONObject> sources = scrollResponse.getSources();
            for (JSONObject source : sources) {
                String content = source.toJSONString();
                System.out.println(content);
            }
            scrollResponseOptional = scrollSourceWithId(hostPort,lastScrollId,time);
        }
        //删除scrollId
        if(lastScrollId != null) {
            deleteScroll(hostPort,Arrays.asList(lastScrollId));
        }
    }

    public static void deleteScroll(String hostPort,List<String> scrollIds) throws IOException {
        String ids = String.join(",", scrollIds);
        String urlBase = "http://%s/_search?scroll/%s";
        String url = String.format(urlBase, hostPort,ids);
        HttpUtil.delete(url);
    }

    /**
     * curl -H 'Content-Type:application/json' -d '{"query":{"match_all":{}}}' http://host:port/index/_search?scroll=10m&search_type=scan
     * @param hostPort e.g. 127.0.0.1:9200
     * @param time e.g. 10m,30s etc
     * @param index
     * @return
     * @throws IOException
     */
    public static Optional<ScrollResponse> scrollSource(String hostPort,String index,String time) throws IOException {
        String urlBase = "http://%s/%s/_search?scroll=%s";
        String url = String.format(urlBase, hostPort, index, time);
        String content = HttpUtil.postJsonContent(url, ESUtil.queryMatchAll());
        return dealScrollBody(content);
    }

    public static Optional<ScrollResponse> scrollSource(String hostPort,String index,String time,int size) throws IOException {
        String urlBase = "http://%s/%s/_search?scroll=%s";
        String url = String.format(urlBase, hostPort, index, time);
        String scrollRequest = ESUtil.scrollFirst(size);
        String content = HttpUtil.postJsonContent(url, scrollRequest);
        return dealScrollBody(content);
    }

    public static Optional<ScrollResponse> scrollSourceWithId(String hostPort,String scrollId,String time) throws IOException {
        String urlBase = "http://%s/_search/scroll";
        String url = String.format(urlBase, hostPort);
        String scrollRequestBody = ESUtil.scrollRequestBody(scrollId, time);
        String result = HttpUtil.postJsonContent(url, scrollRequestBody);
        return dealScrollBody(result);
    }

    private static Optional<ScrollResponse> dealScrollBody(String scrollBody){
        JSONObject result = JSON.parseObject(scrollBody);
        LinkedList<JSONObject> results = new LinkedList<>();
        String scrollId = result.getString("_scroll_id");
        Integer took = result.getInteger("took");
        JSONObject hitsObject = result.getJSONObject("hits");
        if(hitsObject == null){
            return Optional.empty();
        }
        JSONArray hits = hitsObject.getJSONArray("hits");
        for(Object jsonObject : hits){
            JSONObject rs = (JSONObject) jsonObject;
            JSONObject source = rs.getJSONObject("_source");
            results.add(source);
        }
        return Optional.ofNullable(new ScrollResponse(scrollId,took,results));
    }
}
